package com.baseproject.datasource.local.database.dao;

import android.util.Log;

import com.baseproject.BaseApplication;
import com.baseproject.util.LogUtils;

import java.util.HashMap;
import java.util.Map;

public class BaseDaoFactory {

    private DatabaseHelper helper;
    private static BaseDaoFactory instance = new BaseDaoFactory();
    private BaseDaoFactory() {
        helper = new DatabaseHelper(BaseApplication.getApplication());
    }

    Map<String, BaseDao> cacheDaoList = new HashMap<String, BaseDao>();

    /**
     * @param baseDaoClass -->UserDao.Class
     * @param entityClass  -->User.Class
     * @param <T>          BaseDao的子类
     * @param <M>          User的泛型
     * @return
     */
    public synchronized <T extends BaseDao<M>, M> T getBaseDao(Class<T> baseDaoClass, Class<M> entityClass) {
        BaseDao baseDao = null;
        try {
            baseDao = cacheDaoList.get(entityClass.getSimpleName());
            if (baseDao == null) {
                long startTime = System.currentTimeMillis();
                baseDao = baseDaoClass.newInstance();
                baseDao.init(entityClass, helper);
                LogUtils.d("reconstruct baseDao: spend_time = " + (System.currentTimeMillis() - startTime));
                cacheDaoList.put(entityClass.getSimpleName(), baseDao);
            }
        } catch (Exception e) {
            LogUtils.e("getBaseDao Exception: " + Log.getStackTraceString(e));
        }
        return (T) baseDao;
    }

    public static BaseDaoFactory getInstance() {
        return instance;
    }

}
